package api_day10;

import api_day06.Student;
import org.junit.Test;

import java.io.*;
import java.util.Calendar;
import java.util.Date;

/*
 * 测试用
 */
public class TestDemo {
    @Test //新的异常处理
    public void test01(){
        try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src/api_day10/test_copy.txt"));
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src/api_day10/test.txt")))
        {
         int len;
         while ((len = bis.read()) != -1){
             bos.write(len);
         }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Test //字符流的创建于使用
    public void test02() throws IOException {
        File file = new File("src/api_day10/StringOut.txt");
        file.createNewFile();
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/api_day10/StringOut.txt"),"utf-8");
        InputStreamReader isr = new InputStreamReader(new FileInputStream("src/api_day10/StringOut.txt"),"utf-8");
        //特殊值的写入
        osw.write(-1); // Unicode编码 1 字符 = 2 字节 = 16位 写入-1 读取时位16位最大值65535 - 以二进制补码存储的缘故
        osw.write("字符流对象写文件");
        osw.flush();
        int len;
        while ((len = isr.read()) != -1){
            System.out.print(len + " ");
        }
    }
    @Test //对象流测试方法
    public void test03() throws IOException, ClassNotFoundException {
        //对象输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/api_day10/obj.txt"));
        oos.writeObject(new Date());
        Student stu1 = new Student("张三", 18);
        //自定义类需要实现Serializable接口，否则会报NotSerializableException异常
        oos.writeObject(stu1);
        oos.writeObject(Calendar.getInstance());
        //对象输入流
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/api_day10/obj.txt"));
        Object o1 = ois.readObject();
        Object o2 = ois.readObject();
        Object o3 = ois.readObject();
//        Object o4 = ois.readObject();  上面只写入了三个对象，这里读取第四个时会报EOFException异常 -> End Of File
//        字节流读取到末尾返回-1  字符流读取到末尾返回null  对象流读取到末尾返回EOFException异常
        System.out.println(o1);
        System.out.println(o2);
        System.out.println(o3);
    }
}
